<template>
    <div class="app-container">
        <!--车辆信息from表单查询信息 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item :label="$t('vehicle.brand.vehicleBrand')" prop="vehicleBrandId">
                <el-select v-model="queryParams.vehicleBrandId" :placeholder="$t('vehicle.brand.placeholder.vehicleBrand')">
                    <el-option v-for="dict in brandList" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item :label="$t('vehicle.series.modelName')" prop="vehicleSeriesId">
                <el-select v-model="queryParams.vehicleSeriesId" :placeholder="$t('vehicle.series.placeholder.modelName')">
                    <el-option v-for="dict in seriesList" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item :label="$t('vehicle.type.vehicleModel')" prop="vehicleTypeId">
                <el-select v-model="queryParams.vehicleTypeId" :placeholder="$t('vehicle.type.placeholder.vehicleModel')">
                    <el-option v-for="dict in typesList" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item :label="$t('vehicle.vehicle.vehicleManufacturer')" prop="vehicleManufacturer">
                <el-input v-model="queryParams.vehicleManufacturer"
                    :placeholder="$t('vehicle.vehicle.placeholder.vehicleManufacturer')" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item :label="$t('vehicle.vehicle.vehicleVin')" prop="vehicleVin">
                <el-input v-model="queryParams.vehicleVin" :placeholder="$t('vehicle.vehicle.placeholder.vehicleVin')"
                    clearable style="width: 240px" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="IMEI" prop="deviceCode">
                <el-input v-model="queryParams.deviceCode" :placeholder="$t('vehicle.vehicle.placeholder.deviceCode')" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item :label="$t('vehicle.vehicle.binding')" prop="vehicleBinding">
                <el-select v-model="queryParams.vehicleBinding" :placeholder="$t('vehicle.vehicle.placeholder.binding')">
                    <el-option v-for="dict in dict.type.binding_state" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{
                    $t('common.button.query') }}</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.button.reset')
                }}</el-button>
            </el-form-item>
        </el-form>

        <!--车辆新增入口-->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="openImport"
                    v-hasPermi="['device:center:import']">{{ $t('common.button.import') }}</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['vehicle:vehicle:export']">{{ $t('common.button.export') }}</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-files" size="mini" @click="handleSynchronization"
                    v-hasPermi="['vehicle:vehicle:synchronization']">手动同步车厂数据</el-button>
            </el-col> -->
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!--车辆Table信息  -->
        <el-table v-loading="loading" :data="tableData" border style="width: 100%">
            <el-table-column prop="vehicleBrand" :label="$t('vehicle.brand.vehicleBrand')"></el-table-column>
            <el-table-column prop="vehicleSeries" :label="$t('vehicle.series.modelName')"></el-table-column>
            <el-table-column prop="typeName" :label="$t('vehicle.type.vehicleModel')"></el-table-column>
            <el-table-column prop="vehicleManufacturer"
                :label="$t('vehicle.vehicle.vehicleManufacturer')"></el-table-column>
            <el-table-column prop="vehicleNick" :label="$t('vehicle.vehicle.vehicleNike')"></el-table-column>
            <el-table-column prop="vehicleVin" :label="$t('vehicle.vehicle.vehicleVin')"></el-table-column>
            <el-table-column prop="vehicleSecretKey" :label="$t('vehicle.vehicle.secretKey')"></el-table-column>
            <el-table-column prop="vehicleNumber" :label="$t('vehicle.vehicle.licenseNumber')"></el-table-column>
            <el-table-column prop="deviceCode" label="IMEI"></el-table-column>
            <el-table-column prop="iccid" label="ICCID"></el-table-column>
            <el-table-column prop="deviceBlueMac" label="MAC"></el-table-column>
            <el-table-column prop="vehicleMarking" :label="$t('vehicle.vehicle.motorMarked')"></el-table-column>
            <el-table-column prop="userCode" :label="$t('ota.upgrade.userCode')"></el-table-column>
            <el-table-column prop="vehicleColor" :label="$t('vehicle.imgpairing.standard')"></el-table-column>
            <el-table-column :label="$t('vehicle.imgpairing.PictureDisplay')" width="150">
                <template slot-scope="scope">
                    <image-preview :src="scope.row.vehicleImage" :height="66" />
                </template>
            </el-table-column>
            <el-table-column prop="meterBlueName" :label="$t('vehicle.vehicle.meterBlueName')"></el-table-column>
            <el-table-column prop="meterBlueMac" :label="$t('vehicle.vehicle.meterBlueMac')"></el-table-column>
            <el-table-column prop="vehicleParts" :label="$t('vehicle.attachment.associatedParts')"></el-table-column>
            <el-table-column prop="vehicleBinding" :label="$t('vehicle.vehicle.binding')">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.binding_state" :value="scope.row.vehicleBinding" />
                </template>
            </el-table-column>
            <el-table-column fixed="right" :label="$t('common.table.operate')" width="100">
                <template slot-scope="scope">
                    <el-button @click="handleUpdate(scope.row)" type="text" size="small">{{ $t('common.button.edit')
                    }}</el-button>
                    <el-button :disabled="scope.row.vehicleBinding === 1" @click="handleDelete(scope.row)" type="text"
                        size="small">{{ $t('common.button.remove')
                        }}</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页-->
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <vehicle-import ref="vehicleImport" @refreshData="getList"></vehicle-import>

        <!-- 车辆未同步入库的表单 -->
        <el-dialog title="本次同步失败信息" :visible.sync="syncOpen" append-to-body>
            <div class="error-info" title="失败数据和原因">
                <el-tag size="medium" type="danger">{{ errorTitile }}</el-tag>
                <el-statistic :value="failedCount" title="本次同步失败总数"></el-statistic>
            </div>
            <el-table :data="Synchronous" border height="400" style="width: 100%">
                <el-table-column prop="clxh" label="车辆型号"></el-table-column>
                <el-table-column prop="clsbdh" label="车辆车架号"></el-table-column>
                <el-table-column prop="tboximei" label="关联设备IMEI号"></el-table-column>
                <el-table-column prop="fdjh" label="发动机号"></el-table-column>
                <el-table-column prop="csys" label="车辆配色"></el-table-column>
                <el-table-column prop="code4" label="车辆配色"></el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitSyn">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 添加、修改弹窗 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @close="dialogClose">
            <el-form ref="form" :model="form" :rules="rules" label-width="155px">
                <el-row :gutter="15">
                    <el-col :span="12">
                        <el-form-item :label="$t('vehicle.brand.vehicleBrand')" prop="vehicleBrandId">
                            <el-select v-model="form.vehicleBrandId" clearable @change="brandChange"
                                :placeholder="$t('vehicle.brand.placeholder.vehicleBrand')" :style="{ width: '100%' }">
                                    <el-option   v-for="dict in brandList"  :key="dict.value" :label="dict.label"
                                        :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('vehicle.series.modelName')" prop="vehicleSeriesId">
                            <el-select v-model="form.vehicleSeriesId" clearable @change="seriesChange"
                                :placeholder="$t('vehicle.series.placeholder.modelName')" :style="{ width: '100%' }">
                                <el-option v-for="dict in seriesList" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('vehicle.type.vehicleModel')" prop="vehicleTypeId">
                            <el-select v-model="form.vehicleTypeId" clearable  @change="typeChange"
                                :placeholder="$t('vehicle.type.placeholder.vehicleModel')" :style="{ width: '100%' }">
                                <el-option @click="" v-for="dict in typesList" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('vehicle.imgpairing.standard')" prop="vehicleImgId">
                            <el-select v-model="form.vehicleImgId" :style="{ width: '100%' }" clearable>
                                <el-option v-for="dict in imgsList" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('vehicle.vehicle.meterBlueName')" prop="meterBlueName">
                            <el-input v-model="form.meterBlueName"
                                :placeholder="$t('vehicle.vehicle.placeholder.meterBlueName')" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('vehicle.vehicle.meterBlueMac')" prop="meterBlueMac">
                            <el-input v-model="form.meterBlueMac"
                                :placeholder="$t('vehicle.vehicle.placeholder.meterBlueMac')"  />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('vehicle.vehicle.vehicleVin')" prop="vehicleVin">
                            <el-input v-model="form.vehicleVin" :placeholder="$t('vehicle.vehicle.placeholder.vehicleVin')"
                                disabled />
                        </el-form-item>
                    </el-col>
                    
                    <el-col :span="12">
                        <el-form-item :label="$t('vehicle.vehicle.vehicleManufacturer')" prop="vehicleManufacturer">
                            <el-input v-model="form.vehicleManufacturer"
                                :placeholder="$t('vehicle.vehicle.placeholder.vehicleManufacturer')" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('vehicle.vehicle.motorMarked')" prop="vehicleMarking">
                            <el-input v-model="form.vehicleMarking"
                                :placeholder="$t('vehicle.vehicle.placeholder.motorMarked')" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="15">
                        <el-form-item label="IMEI" prop="deviceCode">
                            <el-input  :disabled="biangDeviceCode" v-model="form.deviceCode"
                                :placeholder="$t('vehicle.vehicle.placeholder.deviceCode')" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <el-form-item prop="deviceCode">
                            <el-button :disabled="biangDeviceCode" @click="handleBinding(form)" type="text" size="small">{{
                                $t('vehicle.vehicle.bind') }}</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <el-form-item prop="deviceCode">
                            <el-button :disabled="UntieDeviceCode" @click="handleUntie(form)" type="text" size="small">{{
                                $t('vehicle.vehicle.untie') }}</el-button>
                        </el-form-item>
                    </el-col>
                    
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">{{
                    $t('common.dialog.confirm') }}</el-button>
                <el-button @click="cancel">{{ $t('common.dialog.cancel') }}</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { listBrand } from "@/api/vehicle/brand/data";
import { listSeries } from "@/api/vehicle/series/data";
import { listAttachment } from "@/api/vehicle/attachment/data";
import { listType } from "@/api/vehicle/type/data";
import { exportVehicle, vehicleList, getVehicleInfo, detachVehicle, ListImg, bindVehicle, updateVehicle, delVehicle } from "@/api/vehicle/data";
import vehicleImport from "./vehicleImport.vue";
import { log } from "console";
export default {
    name: "",
    components: { vehicleImport },
    dicts: ['device_status', 'binding_state', 'vehicle_brand', 'vehicle_model', 'vehicle_dis_type'],
    data() {
        return {
            DeleteDeviceCode: false,
            // 按钮loading
            buttonLoading: false,
            UntieDeviceCode: false,
            biangDeviceCode: false,
            title: '',
            // 是否显示弹出层
            open: false,
            imgsList: [],
            typesList: [],
            seriesList: [],
            brandList: [],
            total: 0,
            showSearch: true,
            loading: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                vehicleBrandId: undefined,
                vehicleSeriesId: undefined,
                vehicleTypeId: undefined,
                vehicleManufacturer: "",
                vehicleVin: "",
                deviceCode: "",
                vehicleBinding: undefined
            },
            form: {},
            rules:{
                vehicleBrandId:[
                    {
                        required: true,
                        message: this.$t("vehicle.brand.rules.brand"),
                        trigger: "change",
                    }
                ],
                vehicleSeriesId:[
                    {
                        required: true,
                        message: this.$t("vehicle.brand.rules.series"),
                        trigger: "change",
                    }
                ],
                vehicleTypeId:[
                    {
                        required: true,
                        message: this.$t("vehicle.type.rules.type"),
                        trigger: "change",
                    }
                ],
                vehicleImgId:[
                    {
                        required: true,
                        message: this.$t("vehicle.imgpairing.rules.color"),
                        trigger: "change",
                    }
                ],
                vehicleManufacturer:[
                    {
                        required: true,
                        message: this.$t("vehicle.vehicle.rules.vehicleManufacturer"),
                        trigger: "change",
                    }
                ],
                meterBlueName:[
                    {
                        required: true,
                        message: this.$t("vehicle.vehicle.rules.meterBlueName"),
                        trigger: "change",
                    }
                ],
                meterBlueMac:[
                    {
                        required: true,
                        message: this.$t("vehicle.vehicle.rules.meterBlueMac"),
                        trigger: "change",
                    }
                ]
            },
            tableData: [],
            Synchronous: [],
            syncOpen: false,
            errorTitile: "",
        }
    },
    computed: {
        failedCount() {
            return this.Synchronous.length;
        }
    },
    watch: {},
    created() {
        if (this.$route.query) {
            this.queryParams.deviceCode = this.$route.query.deviceCode;
        }
        this.getList();
        this.getBrandList();
        this.getSeriesList();
        this.getTypeList();
        this.getImgList();
    },
    mounted() { },
    methods: {
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },

        getList() {
            this.loading = true;
            vehicleList(this.queryParams).then(response => {
                this.tableData = response.rows;
                this.total = response.total;
                this.loading = false;
            })
        },

        /**
         * 数据导出
         */
        handleExport() {
          this.download('vehicle/export', {
            ...this.queryParams
          }, `vehicle_${new Date().getTime()}.xlsx`)
        },

        /**
         * 数据同步接口
         */
        handleSynchronization() {
            this.loading = true;
            exportVehicle().then(response => {
                this.loading = false;
                if (response.code == 200 && response.data == null) {
                    this.$message({
                        message: '数据同步完成',
                        type: 'success'
                    })
                    this.getList();
                } else {
                    this.syncOpen = true;
                    this.Synchronous = response.data;
                    this.errorTitile = response.msg;
                }
            })
            this.loading = true;
        },

        submitSyn() {
            this.syncOpen = false;
        },

        cancel() {
            this.open = false;
            this.reset();
        },

        // 表单重置
        reset() {
            this.UntieDeviceCode = false;
            this.biangDeviceCode = false;
            this.form = {
                vehicleBrandId: undefined,
                vehicleSeriesId: undefined,
                vehicleTypeId: undefined,
                vehicleImgId: undefined,
                vehicleColor: undefined,
                vehicleVin: undefined,
                vehicleManufacturer: undefined,
                vehicleMarking: undefined,
                deviceCode: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined
            };
            this.resetForm("form");
        },

        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.buttonLoading = true;
                    if (this.form.vehicleId != null) {
                        console.log(this.form)
                        updateVehicle(this.form).then(response => {
                            this.$modal.msgSuccess();
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    }
                }
            });
        },


        // 车辆和设备绑定
        handleBinding(row) {
            if(this.form.deviceCode){
                var data = {};
            data.vehicleCode = row.vehicleCode;
            data.deviceCode = row.deviceCode;

            bindVehicle(data).then(response => {
                if (response.code == 200) {
                    this.$message({
                        message: this.$t('vehicle.vehicle.bingSuccess'),
                        type: 'success'
                    });
                    this.form.deviceCode = data.deviceCode;
                    this.biangDeviceCode = true;
                    this.UntieDeviceCode = false;
                } else {
                    this.$message.error(this.$t('vehicle.vehicle.bindFluat'));
                }

            })
            }else{
                this.$message.error(this.$t('vehicle.vehicle.bindDevice'));
            }
           
        },

        // 车辆和设备解绑
        handleUntie(row) {
            var data = {};
            data.vehicleCode = row.vehicleCode;
            data.deviceCode = row.deviceCode;

            detachVehicle(data).then(response => {
                if (response.code == 200) {
                    this.$message({
                        message: this.$t('vehicle.vehicle.untieSuccess'),
                        type: 'success'
                    });
                    this.form.deviceCode = '';
                    this.biangDeviceCode = false;
                    this.UntieDeviceCode = true;
                    this.open = false;
                    this.getList();
                } else {
                    this.$message.error(this.$t('vehicle.vehicle.untieFluat'));
                }
            })


        },

        //编辑获取信息
        handleUpdate(row) {
            this.loading = true;
            this.reset();
            const vehicleId = row.vehicleId || this.ids;
            getVehicleInfo(vehicleId).then(response => {
                this.loading = false;
                this.form = response.data;
                console.log(response.data);
                this.getSeriesListByBrandId();
                this.getTypeListByISeriesId();
                this.getImgListByTypeId();
                this.open = true;
                this.title = this.$t('common.button.edit');
                if (response.data.deviceCode != null) {
                    this.biangDeviceCode = true;
                } else if (response.data.deviceCode == null) {
                    this.UntieDeviceCode = true;
                }
            })
        },

        getBrandList() {
            listBrand().then(response => {
                this.brandList = response.rows.map(item => {
                    return {
                        label: item.vehicleBrand,
                        value: item.id
                    }
                })
            })
        },

        getSeriesList() {
            listSeries().then(response => {
                this.seriesList = response.rows.map(item => {
                    return {
                        label: item.vehicleSeries,
                        value: item.id
                    }
                })
            })
        },

        getTypeList() {
            listType().then(response => {
                this.typesList = response.rows.map(item => {
                    return {
                        label: item.typeName,
                        value: item.id
                    }
                })
            })
        },

        getImgList() {
            ListImg().then(response => {
                this.imgsList = response.rows.map(item => {
                    return {
                        label: item.colorDescription,
                        value: item.id
                    }
                })
            })
        },
        brandChange(e){
            console.log(e);
            const brandId = e;
            if (brandId == null || brandId == "") {
               this.clearSeriesList();
               this.clearTypeList();
               this.clearImgList();
                return;
            }
            this.getSeriesListByBrandId();
            this.clearSeriesList();
           
        },
        seriesChange(e){
            console.log(e);
            const seriesId = e;
            if (seriesId == null || seriesId == "") {
               this.clearTypeList();
               this.clearImgList();
                return;
            }
            this.getTypeListByISeriesId();
           this.clearTypeList();
        },
        typeChange(e){
            const imgId = e;
            if (imgId == null || imgId == "") {
               this.clearImgList();
                return;
            }
                
            if (this.form.vehicleTypeId != null) {
               this.getImgListByTypeId();
               this.clearImgList();
            }  
        },
        getVehicleParts(row) {
            this.attachmentTitle = this.$t('vehicle.attachment.associatedParts');
            this.attachmentOpen = true;
            this.attachmenLoading = true;
            var data = {};
            data.typeid = row.id;
            listAttachment(data).then(response => {
                this.attachmentList = response.rows;
                this.attachmenLoading = false;
            })
        },

        openImport() {
            this.$refs['vehicleImport'].init()
        },

        handleDelete(row) {
            const ids = row.vehicleId || this.ids;
            this.$modal.confirm(this.$t('vehicle.type.title.delete') + ids + this.$t('vehicle.type.title.query')).then(() => {
                this.loading = true;
                return delVehicle(ids);
            }).then(() => {
                this.loading = false;
                this.getList();
                this.$modal.msgSuccess();
            }).catch(() => {
            }).finally(() => {
                this.loading = false;
            });
        },
         //对话关闭回调
         dialogClose(){
            console.log("对话框关闭");
            // this.resetForm("dataForm");
            this.$refs['form'].resetFields();
            this.getList();
            this.getBrandList();
            this.getSeriesList();
            this.getTypeList();
            this.getImgList();
        },
        clearSeriesList(){
                this.seriesList = [];
                this.form.vehicleSeriesId = "";
        },
        clearTypeList(){
            this.typesList = [];
            this.form.vehicleTypeId = "";
        },
        clearImgList(){
            this.imgsList = [];
            this.form.vehicleImgId = "";
        },
        getSeriesListByBrandId(){
            var data = {};
            data.brandId = this.form.vehicleBrandId;
            listSeries(data).then(response => {
                this.seriesList = response.rows.map(item => {
                    return {
                        label: item.vehicleSeries,
                        value: item.id
                    }
                })
            })
        },
        getTypeListByISeriesId(){
            var data = {};
            data.seriesId = this.form.vehicleSeriesId;
            listType(data).then(response => {
                this.typesList = response.rows.map(item => {
                    return {
                        label: item.typeName,
                        value: item.id
                    }
                })
            })
        },
        getImgListByTypeId(){
            var data = {};
                data.vehicleTypeId = this.form.vehicleTypeId;
                ListImg(data).then(response => {
                    this.imgsList = response.rows.map(item => {
                        return {
                            label: item.colorDescription,
                            value: item.id
                        }
                    })
                })
        }


    }
}
</script>

<style>
.error-info {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
}
</style>
